function updateCareerCode() {
	var code = 1 * $('select#careerId').val();
	$('#careerCode').val(code);		
}


function fastSearchPatientCodeCustomize(searchString, controller, actionName , divIdFillSearchResult, redirect, codePrefix, patientCode) {
	
	if (searchString != '') {
		$('#quickSearch').val(_("Searching..."));
		$.ajax ({
			type:     "POST",
			url:	  "../PatientFinder/fastSearchPatientCode?set_ajax_view",
			data: 	  "patientCode=" + searchString
					 +"&controller=" + controller
					 +"&actionName=" + actionName
					 +"&redirect=" + redirect
					 +"&insurance=" + $('#insurance').val()
			,			
			dataType: "json",
			success:  function(data) {
				$('#quickSearch').val(searchString);
				if (data.error.code == 'OK') {
					if (redirect == 1) {
						window.location = data.result;
					} else {
						$('div#' + divIdFillSearchResult).html(data.result);
						$('#examineBtn').focus();	
						
					}
					
				} else {
					//reset form 					
					$.ajax ({
						type:    "POST",
						data:    "insurance=" + $('#insurance').val(),
						url:	 "../OdonReception/Cancel?set_ajax_view",								
						success: function(data) {							
							$('#odonReception').html(data);
							$('#patientCodePreFix').val(codePrefix);
							$('#patientCode').val(patientCode);
							
							$('#personName').focus();
							$('#personName').select();							
						}
					});
				}
				
			}
		});
	}
}

function suggestCareer(event, nextId) {
	if (event.which == 13){
		$('#' + nextId).focus();
	} else {
		var code = $.trim($('input#careerCode').val());
		if (code == '') {
			$('select#careerId').val(0);
			return;
		}
		var codeInt = 1 * code;
		var caId = $('input#career' + codeInt).val();
		if (caId != undefined) {
			$('select#careerId').val(caId);		
		} else {
			$('select#careerId').val(0);
		}
	}
}

function checkSelectGender() {
	if ($('#genderMale').is(':checked') || $('#genderFemale').is(':checked')) {
		$('span#statusMessage').text("").hide();
		return true;
	}
	$('span#statusMessage').text(_("Not yet select gender")).show();
  	return false;
}

function checkBirthday(objYear, objMonth, objDay) {
   		var res 	= 	checkDate(objYear, objMonth, objDay, true, _('Empty date of birth'), 'statusMessage', true);
   		if(!res){
   			return false;
   		}
   		$('input#personAge').css("border-color", "#AAA");
   		getAge('birthday','personAge');
   		return true;   	
}

function isReadyToSubmit() {
	
	/*
	 * Generate patient code automatically
	 * 
	if (!isNotEmpty($('input#patientCode'), _('Empty patient code'), 'statusMessage')) {
		return false;
	}
	*/
	if (!isNotEmpty($('input#personName'), _('Empty name'), 'statusMessage')) {
		return false;
	}
	if (!checkSelectGender()) {
		return false;
	}
	if (!checkBirthday($('input#birthday'),$('input#DOB_mm'), $('input#DOB_dd'))) {
		return false;
	}
	
	if(!checkNumber($('input#personPhoneNumber'), _("Invalid phone number"), 'statusMessage', '#AAA')){
		return false;
	}
	if($('input#patientRelativeNumber').val() != '' && !(checkNumber($('input#patientRelativeNumber'), _("Invalid phone number"), 'statusMessage', '#AAA'))){
		return false;
	}
		
	return true;
}


function checkAge(obj) {
	var lcInt = locale(decimalPoint, thousandSep, 0);
	if (!validateNumberByLocal($('#personAge'), lcInt, true, _("Age must between {0} and {1}",0,100) , 'statusMessage')) {
		return false;
	}
	
	if (!checkIntMinMax('personAge', 0, 100, 'statusMessage',
			_("Age must between {0} and {1}",0,100))) {
		return false;
	}
   		obj.css("border-color", "#AAA");
   		$('input#birthday').css("border-color", "#AAA");
   		$('input#DOB_mm').css("border-color", "#AAA");
   		$('input#DOB_dd').css("border-color", "#AAA");
   		$('span#statusMessage').text('');
   		getBirthday('personAge','birthday');
   	
}

function provinceChange(provinceId, districtId, wardId) {
	$.ajax ({
		type:    "GET",
		url:	  "../OdonReception/getDistrictFromProvinceAjax?set_ajax_view",
		data:	  "proviceId=" + $('#' + provinceId).val(),
		dataType: "json",
		success:	function(data) {
			if(data.districtList.length > 0){
				$('#' + districtId).html(data.districtList);
			}else{
				var option = "<option value='0' label='- " + _('District') + " -'>- " + _('District') + " -</option>";
				$('#' + districtId).html(option);
			}
						
		}
	});
}



function resetForm() {
	$.ajax ({
		type:    "POST",
		data: 	"&insurance=" + $('#insurance').val(),
		url:	 "../OdonReception/Cancel?set_ajax_view",				
		beforeSend: function() {
			$('#ajaxLoader').show();						
		},
		complete: function() {
			$('#ajaxLoader').hide();
		},
		success: function(data) {
			$('#odonReception').html(data);			
			$('#patientCode').focus();			
		}
	});
	
}


function registerPatient() {			
	var submitData = $('#addDemographicsForm').serialize() +
			'&' + $('#addInsuranceForm').serialize();	
	$.ajax ({
		// Prevent user enter speedy many times which would create many patients
		async:	false,
		type:    "POST",
		url:	 "../OdonReception/RegisterPatientAjax?set_ajax_view",
		data:	 submitData,
		dataType: "json",
		beforeSend: function() {
			$('#ajaxLoader').show();
			
		},		
		success: function(data) {
			$('#ajaxLoader').hide();
			if (data.error.code == 'OK') {
				
				//print patient code
				var buttons = {};
				buttons[_('Close')] = function() {
					resetForm();					
					$(this).dialog('close');		
				};
				buttons[_('Print')] = function() {
					printTreatmentTicket(data.result.id, data.result.recordId);
					resetForm();					
					$(this).dialog('close');
				};
				var mess = _('Patient code: {0}', '<span style="font-size: 1.2em; font-weight: bold;">' + data.result.code + '</span>');
				generalDialog(null,_('Register successfully'),mess,null,{
					autoOpen: true,			
					bgiframe: true,
					resizable: false,		
					width: 250,
					height: 150,
					modal: true,
					buttons: buttons,
					dialogClass: 'custom-dialog'					
				},_('Print'));
				
			} else {
				displayError(data.error.mess);	
			}
		}
	});
}


function savePatient() {	
	
	var submitData = $('#addDemographicsForm').serialize() + 
			'&' + $('#addInsuranceForm').serialize();	
	
	$.ajax ({
		type:    "POST",
		url:	 "../OdonReception/SavePatientAjax?set_ajax_view",
		data:	 submitData,
		dataType: "json",
		beforeSend: function() {
			showMessage('statusMessageSave', '', 'success');
			$('#ajaxLoader').show();
		},
		complete: function() {
			$('#ajaxLoader').hide();
		},
		success: function(data) {
			if (data.error.code == 'OK') {
				$('#patientCode').text(data.result.code);
				$('#patientId').val(data.result.id);
				
				$('#insuraceCardInfo').show();
				$('#newInsuranceCardBtn').focus();
				showMessage('statusMessageSave', _('Save successful'), 'success');
			} else {
				displayError(data.error.mess);	
			}
			
		}
	});
}

function autoTab(thisElem, maxLength, nextElem){
	if(thisElem.value.length == maxLength){
		thisElem.blur();
		$('#' + nextElem).focus();
		$('#' + nextElem).select();
	}
}

function printTreatmentTicket(patientId, recordId) {
	var codePrefix = $.trim($('#patientCodePreFix').val());	
	var url='../OdonReception/PrintTreatmentTicket?set_print_view&patientId=' 
		+ patientId + '&recordId=' + recordId + '&codePrefix=' + codePrefix;		
	window.open(url, '', 'scrollbars=yes, menubar=no, height=700, width=800, resizable=yes, toolbar=no, location=no, status=no');
}


function confirmDeletePatient() {
    var patientId   =   $('input#patientId').val();
    var patientName =   $('input#personName').val();
    if (patientId == '' || $.trim(patientName) == '') {
    	return false;
    }
	var buttons = {};
	buttons[_('Cancel')] = function() {
	    $(this).dialog('close');        
	};
	buttons[_('Ok')] = function() {
	    $(this).dialog('close');
	    deletePatient(patientId);
	};
	var title  =   _('Delete patient');
	var msg  =   "<div style='margin-bottom: 10px; height: 30px; display: block;'>" + _("Are you sure to delete patient: <span class='impression'>{0}</span>?", patientName) + "</div>";
	msg  +=    "<div style='height: 30px; display: block;'><div style='width: 50px; float: left;'><span>" + _('Note') + ": </span></div><div style='float: left;'>" + _('All the related information will be deleted') + "</div></div>";
	msg  +=    "<div style='height: 30px; display: block;'><div style='width: 50px; float: left;'>&nbsp;</div><div style='float: left;'><span class='impression'>" + _('Demographic information') + "</span></div></div>";
	msg  +=    "<div style='height: 30px; display: block;'><div style='width: 50px; float: left;'>&nbsp;</div><div style='float: left;'><span class='impression'>" + _('Medical records') + "</span></div></div>";
	msg  +=    "<div style='height: 30px; display: block;'><div style='width: 50px; float: left;'>&nbsp;</div><div style='float: left;'><span class='impression'>" + _('Payment information') + "</span></div></div>";
	generalDialog(null, title, msg, null,{
	    autoOpen: true,         
	    bgiframe: true,
	    resizable: false,       
	    width: 430,
	    height: 280,
	    modal: true,
	    buttons: buttons,
	    dialogClass: 'custom-dialog'                    
	},_('Cancel'));
}

function deletePatient(patientId, confirmed) {    
    $.ajax ({
        type:    "POST",
        url:     "../OdonReception/deletePatientAjax?set_ajax_view",
        data:    "patientId=" + patientId,
        dataType: "json",
        beforeSend: function() {
            $('#ajaxLoader').show();            
        },
        complete: function() {
            $('#ajaxLoader').hide();
        },
        success: function(data) {
            if (data.error.code == 'OK') {
            	resetForm();            	               
            } else {
                displayError(data.error.mess);  
            }
        }
    });
}

function saveServicePatient() {
	if (!isReadyToSubmit()) {
		return;
	}
	
	savePatient();
}

function saveInsurancePatient() {
	if (!isReadyToSubmit()) {
		return;
	}
	
	if (!isReadyToSubmitInsurance('statusMessage')) {
		return;
	}
	
	savePatient();
}

function registerServicePatient() {
	if (!isReadyToSubmit()) {
		return;
	}
		
	registerPatient();
}

function registerInsurancePatient() {
	if (!isReadyToSubmit()) {
		return;
	}
	
	if (!isReadyToSubmitInsurance('statusMessage')) {
		return;
	}
	
	registerPatient();
}

